#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/08/19 10:50
# @Author  : daikeliang
# @File    : portfolio_interface.py
# @Comment :
# @Software: PyCharm

"""
脚本说明：取阿里云组合数据的接口
"""
import requests
import time
import json
import hashlib

from quant_researcher.quant.project_tool.exception import FOFServerError, ERR_S_1
from quant_researcher.quant.project_tool.conf import LOCAL_CONF


def get_portfolio_info_with_id(func_number, data, paging=False):
    """
    根据组合ID和功能号获取组合的相关数据

    :param func_number: 功能号ID
    :param data: 组合ID，形如{"combination_id": "270"}
    :param paging: 是否分页，分页与不分页的接口返回数据格式不一样
    :return:
    """
    # 从配置文件里读取是生产环境还是测试环境
    source = LOCAL_CONF['factor-computation']['source_4_portfolio']
    if source == 'prod':
        system_id = 'SIMULATE_FUND'
        company_id = 'THINKIVE'
        sign_key = '243D73C8D635A0A3DB3C0686D9C10D1A'
        timestamp = int(time.time() * 1000)

        json_data = json.dumps(data)
        sign_str = f'company_id={company_id}&data={json_data}&funcNo={func_number}&signKey={sign_key}&system_id={system_id}&timestamp={timestamp}'
        sign = hashlib.md5(sign_str.encode('utf-8')).hexdigest().upper()

        url = 'http://8.129.217.27:8090/servlet/access'
        url = f'{url}?data={json_data}&company_id={company_id}&system_id={system_id}&funcNo={func_number}&sign={sign}&timestamp={timestamp}'
    elif source == 'test':
        params = ''
        for k, v in data.items():
            params += f'&{k}={v}'

        url = 'http://192.168.90.66:9069/servlet/json'
        url = f'{url}?funcNo={func_number}{params}'
    else:
        raise NotImplementedError

    try:
        response = requests.get(url)
        if response.status_code == 200:
            response = response.json()
            if response['error_no'] == '0':
                if len(response['results']) != 0:
                    if paging:
                        return response['results'][0]['data']
                    else:
                        return response['results']
                else:
                    return None
            else:
                return None
        else:
            return None
    except Exception:
        raise FOFServerError(ERR_S_1, f'调用组合接口时出错，功能号：{func_number}，入参：{data}，paging：{paging}')


if __name__ == '__main__':
    # get_portfolio_info_with_id(403143, {"combination_id": "1189"})
    portfolio_info = get_portfolio_info_with_id(403403, {"combination_id": "1047", 'start_date':
                                                         '20200701', 'end_date': '20210301'})
    # aaa = get_portfolio_info_with_id(406009, {"combination_id": "289"})
